<!--
 * @Date: 2025-06-30 17:57:06
 * @LastEditTime: 2025-07-04 10:12:22
-->
<template>
  <a-spin :spinning="loading">
    <div class="info-confirm-wrapper">
      <div class="info-confirm-section">
        <div class="info-row">
          <span class="info-label">任务名称：</span>
          <span class="info-value">{{
            localBaseConfig.flowName
          }}</span>
          <!-- <a-input
            v-else
            v-model:value="localBaseConfig.flowName"
            style="width: 300px"
          /> -->
        </div>
        <div class="info-row">
          <span class="info-label">任务描述：</span>
          <span class="info-value" v-if="!isEditMode">{{
            localBaseConfig.flowDesc
          }}</span>
          <a-textarea
            v-else
            v-model:value="localBaseConfig.flowDesc"
            style="width: 300px"
          />
        </div>
        <div class="info-row">
          <span class="info-label">数据源：</span>
          <img
          :src="loadImg(`smallIcon/${localBaseConfig.dbType ? localBaseConfig.dbType : 'null'}.png`)"
            alt="mysql"
            class="info-icon"
          />
          <span class="info-value">{{ localBaseConfig.dbType }}</span>
        </div>
        <div class="info-row">
          <span class="info-label">程序执行节点：</span> 
          <span class="info-value">{{ localBaseConfig.mac_name }}</span>
        </div>
        <div class="info-row">
          <span class="info-label">选择目标库类型：</span>
          <span class="info-value">{{ localBaseConfig.reserve2 }}</span>
        </div>
      </div>
      <div class="info-confirm-section">
        <div class="info-row">
          <span class="info-label">评估对象类型：</span>
          <div class="info-checkbox-group">
            <a-checkbox
              v-for="item in objectTypeOptions"
              :key="item.objTypeId"
              :checked="item.isSelect === 1"
              :disabled="!isEditMode"
              @change="(e) => handleObjectTypeChange(item.id, e.target.checked)"
              >{{ item.objType }}</a-checkbox
            >
          </div>
        </div>
      </div>
      <div class="info-confirm-section">
        <div class="info-row">
          <span class="info-label">评估对象：</span>
          <div class="info-checkbox-group">
            <a-transfer
              v-model:target-keys="targetKeys"
              :data-source="mapping"
               :disabled="!isEditMode"
              :titles="['未选评估对象', '已选择评估对象']"
              :render="(item) => item.operateResources"
              :list-style="{ width: '400px', height: '400px' }"
            />
          </div>
        </div>
      </div>
      <div class="info-confirm-section adv-section">
        <div class="adv-title">高级配置：</div>
        <div class="info-row">
          <span>采集并发：</span>
          <a-input-number
            :min="1"
            :max="10"
             :disabled="!isEditMode"
            v-model:value="detailConfig.thread"
            style="width: 80px"
          />
        </div>
        <div class="info-row">
          <span>采集时间：</span>
            <a-radio-group  :disabled="!isEditMode" v-model:value="detailConfig.timeType">
              <a-radio value="0">所有时间段</a-radio>
              <a-radio value="1">指定时间段</a-radio>
            </a-radio-group>
            <template v-if="detailConfig.timeType === '1'">
              <a-date-picker
                :disabled="!isEditMode"
                v-model:value="detailConfig.startTime"
                placeholder="选择开始时间"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="margin-left: 12px; width: 160px"
                show-time
              />
              <a-date-picker
                :disabled="!isEditMode"
                v-model:value="detailConfig.endTime"
                placeholder="选择结束时间"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="margin-left: 8px; width: 160px"
                show-time
              />
            </template>
          <template>
          </template>
        </div>
        <div class="info-row">
          <span>探测敏感信息：</span>
            <a-radio-group  :disabled="!isEditMode" v-model:value="detailConfig.sensitiveType">
              <a-radio value="1">是</a-radio>
              <a-radio value="0">否</a-radio>
            </a-radio-group>
            <template v-if="detailConfig.sensitiveType === '1'">
              <span style="margin-left: 12px">探测行数：</span>
              <a-input-number
                :disabled="!isEditMode"
                v-model:value="detailConfig.rows"
                :min="1"
                :max="1000"
                style="width: 80px"
              />
            </template>
        </div>
      </div>
    </div>
    <div class="flex justify-center">
      <template v-if="isEditMode === 'view'">
        <a-button type="primary"  @click="handleCancel">取消</a-button>
      </template>
      <template v-else-if="!isEditMode">
        <a-button type="primary"  @click="prev" style="margin-right: 10px">上一步</a-button>
        <a-button type="primary"  @click="next">完成</a-button>
      </template>
      <template v-else>
        <a-button type="primary"  @click="handleCancel">取消</a-button>
        <a-button type="primary"  @click="handleSave">保存</a-button>
      </template>
    </div>
    <verifyLog ref="verifyLogRef" />
  </a-spin>
</template>

<script setup>
import {
  Checkbox as ACheckbox,
  Radio as ARadio,
  RadioGroup as ARadioGroup,
  message,
  Modal,
  Spin,
} from "ant-design-vue";
import { ref, defineEmits, onMounted, reactive, watch } from "vue";
import * as http from "@/api/flow/createTask";
import verifyLog from "./startauto.vue";
import { useStore } from "vuex";
import dayjs from "dayjs";
import { loadImage } from "@/hooks/loadImg";
const { loadAllPathImg } = loadImage();
function loadImg(url) {
  return loadAllPathImg(url);
}

const store = useStore();

const props = defineProps({
  record: Object,
  isEditOnline: { type: String, default: "edit" },
});

const isEditMode = ref(false);
const localBaseConfig = ref({});
const detailConfig = reactive({
  thread: 1,
  timeType: "0",
  startTime: null,
  endTime: null,
  sensitiveType: "0",
  rows: 1000,
});
const objectTypeOptions = ref([]);
const targetKeys = ref([]);
const emit = defineEmits(["next", "prev", "close"]);
const mapping = ref([]);
const loading = ref(false);

async function handleSave() {
  // 这里可以调用接口保存，也可
  await saveConfig()
  // 保存的时候再调用下仅限于当前方法
  verifyLogRef.value.savaIsEditMode();
  emit('close');
  isEditMode.value = false;
}
const handleObjectTypeChange = (valId, checked) => { 
  const item = objectTypeOptions.value.find(item => item.id === valId);
  if (item) {
    item.isSelect = checked ? 1 : 0;
  }
  console.log(objectTypeOptions.value, 'objectTypeOptions.value')
}
// 保存
const saveConfig = async () => {
  delete localBaseConfig.value.createTime
  delete localBaseConfig.value.mac_name
  let dataJson = {
    objType: objectTypeOptions.value,
    mapping: mapping.value,
    detailConfig,
    baseConfig: localBaseConfig.value
  }
  let params = {
    flowId: props.record.flowId,
    dataJson: JSON.stringify(dataJson)
  }
  return await http.saveConfig(params)
}
function handleCancel() {
  // localBaseConfig.value = { ...props.record };
  emit('close');
  isEditMode.value = false;
}

const next = () => {
  if (verifyLogRef.value) {
    verifyLogRef.value.openModel(1);
  }
};
const prev = () => {
  emit("prev");
};
const verifyLogRef = ref();

// 查询获取数据
async function queryConfig(flowId) {
  loading.value = true;
  let params = {
    flowId,
  };
  let res = await http.queryConfig(params);
  try {
    if (res.code === "000000") {
      // 第一步信息
      localBaseConfig.value = res.data.baseConfig;
      // 反显下
      queryAllHostInfo()
      if (props?.record?.userGroupId) {
        getDataSourcePageInfo();
      }

      // 评估对象类型
      objectTypeOptions.value = res.data.objType;
      objectTypeOptions.value.forEach((item) => {
        item.value = item.id;
      });
      // 评估对象范围
      mapping.value = res.data.mapping;
      mapping.value.forEach((item) => {
        item.key = item.operateResources;
        if (item.isSelect === 1) {
          targetKeys.value.push(item.operateResources);
        }
      });
      // 确认信息
      if (res.data.detailConfig) {
        detailConfig.thread = res.data.detailConfig.thread;
        detailConfig.timeType = res.data.detailConfig.timeType;
        detailConfig.startTime = dayjs(res.data.detailConfig.startTime).format('YYYY-MM-DD HH:mm:ss');
        detailConfig.endTime = dayjs(res.data.detailConfig.endTime).format('YYYY-MM-DD HH:mm:ss');
        detailConfig.sensitiveType = res.data.detailConfig.sensitiveType;
        detailConfig.rows = res.data.detailConfig.rows;
      }
    }else{
      message.error(res.msg);
    }
  } catch (error) {
    message.error(error);
    console.log(error);
  } finally {
    loading.value = false;
  }
}
// 获取主机列表
const queryAllHostInfo = async () => {
  let params = {
    userID:window.sessionStorage.getItem("userId"),
  }
  let res = await http.queryAllHostInfo(params);
  try {
    localBaseConfig.value.mac_name = res.data.rows.find(item => item.mac_id === localBaseConfig.value.macId).host_name
  } catch (error) {
    console.log(error);
    message.error(error);
  }
};
// 获取数据源
const getDataSourcePageInfo = async () => {
  let params = {
    userID: window.sessionStorage.getItem("userId"),
    groupId: props.record.userGroupId,
    db_id: localBaseConfig.value.db_id,
    engineID: "",
  };
  let res = await http.getDataSourcePageInfo(params);
  try {
    localBaseConfig.value.db_alias_name = res.data.rows[0].db_alias_name
  } catch (error) {
    console.log(error);
    message.error(error);
  }
};

onMounted(() => {
  //回显数据
  if (props.record && props.record.flowId) {
    if (props.isEditOnline === "edit"){
      isEditMode.value = true;
    } else if (props.isEditOnline === "view"){
      isEditMode.value = 'view';
    } else {
      isEditMode.value = false;
    }
    queryConfig(props.record.flowId);
  } else {
    queryConfig(store.state.taskInfo.flowId);
  }
  console.log(isEditMode, 'isEditMode')
});
</script>

<style scoped>
.info-confirm-wrapper {
  width: 100%;
  max-width: 1100px;
  margin: 0 auto;
  padding: 48px 0 32px 0;
}
.info-confirm-section {
  margin-bottom: 36px;
}
.info-row {
  display: flex;
  align-items: flex-start;
  flex-wrap: wrap;
  margin-bottom: 36px;
}
.info-label {
  color: #222;
  font-weight: 500;
  min-width: 120px;
  margin-right: 16px;
  display: inline-block;
  text-align: right;
  font-size: 16px;
}
.info-value {
  margin-right: 48px;
  min-width: 80px;
  color: #333;
  font-size: 16px;
}
.info-checkbox-group {
  display: flex;
  flex-wrap: wrap;
  gap: 20px 32px;
  margin-top: 2px;
  max-width: 900px;
}
.adv-section {
  margin-bottom: 40px;
}
.adv-title {
  font-weight: 600;
  font-size: 17px;
  color: #1890ff;
  margin-bottom: 18px;
}
.adv-row {
  display: flex;
  flex-wrap: wrap;
  gap: 32px 64px;
  margin-bottom: 12px;
}
.adv-item {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}
.adv-label {
  color: #444;
  font-weight: 500;
  min-width: 90px;
  margin-right: 8px;
  font-size: 15px;
}
.adv-value {
  color: #222;
  font-size: 15px;
}
.info-icon {
  width: auto;
  height: 22px;
  vertical-align: middle;
  margin-right: 6px;
}
@media (max-width: 900px) {
  .info-confirm-wrapper {
    padding: 18px 4vw 8px 4vw;
  }
  .info-label {
    min-width: 90px;
    font-size: 15px;
  }
  .info-checkbox-group {
    max-width: 100vw;
    gap: 12px 12px;
  }
  .adv-row {
    gap: 16px 16px;
  }
}
</style>
